package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.CircleImageView;
import com.ihighest.app.infox.tools.LoopListener;
import com.ihighest.app.infox.tools.LoopView;

public class SetNameAndIconActivity extends BaseActivity implements OnClickListener {
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private ActivityTitle title;
	private CircleImageView iconImageView;
	private EditText nameEditText, doEditText;
	private ImageView selectdo;

	private PopupWindow mPopupWindow;
	private RelativeLayout.LayoutParams layoutParams;
	private LoopView loopView;
	private LinearLayout rootview;
	private String a;
	private Bitmap myBitmap;
	/* 头像名称 */
	private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	private File tempFile;
	private String imgPath;
	private Uri photoUri;
	private String mJob;
	private ArrayList<String> list;
	private String activityName;
	private ArrayList<String> stepList;
	private Intent intent;
	private View falesparent;
	private String ueseIcon;
	private String name;
	String nickName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		setContentView(R.layout.infox_activity_setting_iconandname);
		activityName = getIntent().getStringExtra("personActivity");
		title = (ActivityTitle) findViewById(R.id.id_setnameandicon_title);
		title.setTitle("设置头像和昵称");
		ueseIcon = getIntent().getStringExtra("icon");
		name = getIntent().getStringExtra("name");
		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("完成");
		title.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 完成提交
				nickName = nameEditText.getText().toString();
				if (nickName.length() > 8) {
					ToastKit.showShort(SetNameAndIconActivity.this, "输入的昵称过长");
					return;
				}
				if (nickName.equals(name)) {
					commitData(nickName, mJob);
					finish();
				} else {
					checkname(nickName);

				}
				// commitData(nickName, mJob);
				// finish();
			}

		});
		inint();

	}

	private void checkname(String uname) {
		// TODO Auto-generated method stub
		Api.post("me/checkUnameExist", ApiParam.create().addParam("uname", uname), new ApiCallback(SetNameAndIconActivity.this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				// TODO Auto-generated method stub
				if (result.getCode() == 100) {
					try {
						if (result.getData().getBoolean("result")) {
							ToastKit.showShort(SetNameAndIconActivity.this, "该昵称已存在");
						} else {
							commitData(nickName, mJob);
							finish();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub
              ToastKit.showShort(SetNameAndIconActivity.this, "昵称校验失败，请重试");
			}
		}, SetNameAndIconActivity.this);

	}

	private void inint() {
		tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
		iconImageView = (CircleImageView) findViewById(R.id.id_icon_imageview);
		nameEditText = (EditText) findViewById(R.id.id_name_edit);
		doEditText = (EditText) findViewById(R.id.id_do_edit);
		selectdo = (ImageView) findViewById(R.id.id_selectdo_imageview);
		String from = getIntent().getStringExtra("personActivity");

		iconImageView.setOnClickListener(this);

		selectdo.setOnClickListener(this);

		findViewById(R.id.chooseJob).setOnClickListener(this);

		if (!(from == null || from.equals(""))) {

			if (!TextUtils.isEmpty(name)) {
				nameEditText.setText(name);
				nameEditText.setSelection(name.length());
			}

			// String url = SharedPreferencesKit.getString(this,
			// Const.SP_KEY_USER_HEADER);
			// String name = SharedPreferencesKit.getString(this,
			// Const.SP_KEY_USER_NAME);
			String profession = SharedPreferencesKit.getString(this, Const.PROFESSION);
			//
			// DisplayImageOptions defaultOptions = new
			// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_person_no_icon)
			// .showImageOnFail(R.drawable.infox_person_no_icon).showImageOnLoading(R.drawable.infox_person_no_icon)
			// .cacheInMemory(true).cacheOnDisc(true).build();
			// ImageLoader.getInstance().displayImage(ueseIcon, iconImageView,
			// defaultOptions);
			AppKit.SetUserImg(ueseIcon, iconImageView);
			doEditText.setText(profession);

		}

		getData();

	}

	private void getData() {
		Api.data("position_type_list.json", new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				list = new ArrayList<String>();
				if (result.getDatas() != null) {
					for (int i = 0; i < result.getDatas().length(); i++) {
						try {
							list.add(result.getDatas().get(i).toString());
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				}
				initPupoVindow();

			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, SetNameAndIconActivity.this);

	}

	private void initData(View v) {
		layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

		rootview = (LinearLayout) v.findViewById(R.id.mRootView);

		falesparent = v.findViewById(R.id.id_falseparent);
		falesparent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mPopupWindow.dismiss();
			}
		});

		loopView = new LoopView(this);
		TextView view = new TextView(SetNameAndIconActivity.this);
		view.setLayoutParams(new LayoutParams(layoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		view.setBackgroundResource(R.drawable.infox_send_back);
		view.setText("确定");
		view.setTextSize(20.0f);
		view.setTextColor(Color.WHITE);
		view.setGravity(Gravity.CENTER);

		// 设置是否循环播放
		loopView.setNotLoop();
		// 滚动监听
		loopView.setListener(new LoopListener() {

			@Override
			public void onItemSelect(int item) {
				a = list.get(item);
			}
		});
		// 设置原始数据
		loopView.setArrayList(list);
		// 设置初始位置
		loopView.setPosition(0);
		// 设置字体大小
		loopView.setTextSize(16);
		rootview.addView(loopView, layoutParams);
		rootview.addView(view);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int selectItem = loopView.selectItem();
				mJob = list.get(selectItem);
				doEditText.setText(list.get(selectItem));
				// Toast.makeText(SetNameAndIconActivity.this,
				// list.get(selectItem), 0).show();
				mPopupWindow.dismiss();
			}
		});
	}

	private void initPupoVindow() {
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_pupopwindow_scrollitem_layout, null);
		initData(popupWindow);

		// 创建一个PopupWindow
		// 参数1：contentView 指定PopupWindow的内容
		// 参数2：width 指定PopupWindow的width
		// 参数3：height 指定PopupWindow的height
		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
	}

	private void showPupop() {

		if (mPopupWindow == null) {
			initPupoVindow();
			mPopupWindow.showAtLocation(SetNameAndIconActivity.this.findViewById(R.id.id_parent_view), Gravity.CENTER, 0, 0);
		} else {
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			} else {
				mPopupWindow.showAtLocation(SetNameAndIconActivity.this.findViewById(R.id.id_parent_view), Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 * 
	 * @author lkx Created at 2015-10-17 下午5:49:21
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.id_icon_imageview:
			// 选择图像
			// PopupWindow

			// PictureUtil.doPickPhotoAction(SetNameAndIconActivity.this);
			new AlertDialog.Builder(this).setTitle("选择图片获取方式").setNegativeButton("相册", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					// 激活系统图库，选择一张图片
					Intent intent = new Intent(Intent.ACTION_PICK);
					intent.setType("image/*");
					startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

				}
			}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int whichButton) {

					Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
					// 判断存储卡是否可以用，可用进行存储
					if (hasSdcard()) {
						ContentValues values = new ContentValues();
						photoUri = SetNameAndIconActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								values);
						intent.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
					}
					startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
				}
			}).show();
			// Intent intent = new Intent(
			// "android.media.action.IMAGE_CAPTURE");
			// // 判断存储卡是否可以用，可用进行存储
			// if (hasSdcard()) {
			// ContentValues values = new ContentValues();
			// photoUri = SetNameAndIconActivity.this
			// .getContentResolver()
			// .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
			// values);
			// intent.putExtra(
			// MediaStore.EXTRA_OUTPUT,
			// Uri.fromFile(new File(
			// Environment
			// .getExternalStorageDirectory(),
			// PHOTO_FILE_NAME)));
			// }
			// startActivityForResult(intent,
			// PHOTO_REQUEST_CAMERA);
			//
			// }
			// }).show();

			break;

		case R.id.chooseJob:
			showPupop();
			break;
		}

	}

	/**
	 * 提交昵称和职位数据
	 * 
	 * @param name
	 * @param job
	 * 
	 * @author lkx Created at 2015-10-17 下午5:49:24
	 */
	private void commitData(final String name, String job) {
		ApiParam param = ApiParam.create();

		String s = null;
		try {
			s = SharedPreferencesKit.getJsonObject(SetNameAndIconActivity.this, Const.SP_KEY_CONFIG_JSON).getString("reg_optional_step");
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		stepList = new ArrayList<String>();
		if (!TextUtils.isEmpty(s)) {
			String[] strs = s.split(",");
			for (int i = 0; i < strs.length; i++) {
				stepList.add(strs[i]);
			}
		}

		if (TextUtils.isEmpty(name)) {
			ToastKit.showShort(getApplicationContext(), "请输入昵称");
		} else {

			param.addParam("nick_name", name);
			if (!TextUtils.isEmpty(job)) {
				param.addParam("profession", job);
			}

			Api.post("me/profile", param, new ApiCallback(SetNameAndIconActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					if (result.getCode() == 100) {
						SharedPreferencesKit.putString(mContext, Const.SP_KEY_USER_NAME, name);
						AppKit.refreshRongIMUser(mContext);
					}

				}

				@Override
				public void handleFailure(Exception e, String msg) {

				}

			}, SetNameAndIconActivity.this);
			if (TextUtils.isEmpty(activityName)) {
				// 如果该值为空，表示是注册界面进入该界面的，点击完成进入绑定标签界面
				Intent inten = new Intent(SetNameAndIconActivity.this, LableBindingActivity.class);
				startActivity(inten);
				if (stepList != null) {
					Intent intent = null;
					switch (stepList.get(0)) {
					case "tag":
						// 绑定标签
						intent = new Intent(SetNameAndIconActivity.this, LableBindingActivity.class);
						break;

					case "columnist":
						// 订阅专栏
						intent = new Intent(SetNameAndIconActivity.this, SubscriptionColumnActivity.class);
						break;
					case "enterprise":
						// 订阅企业号
						intent = new Intent(SetNameAndIconActivity.this, SubscriptionColumntwoActivity.class);
						break;

					}
					if (stepList.size() >= 1) {
						// 如果步骤很多，将步骤数据传给第一个界面
						stepList.remove(0);
						intent.putStringArrayListExtra(Const.STEPLIST, stepList);
					}
					startActivity(intent);
				} else {
					Intent intent2 = new Intent(SetNameAndIconActivity.this, MainActivity.class);
					startActivity(intent2);
					finish();
				}
			} else {
				// 如果有值则表示是我界面进入该界面设置头像！完成之后直接关闭该界面
				finish();
			}

		}

	}

	/**
	 * 图片上传
	 * 
	 * 
	 * @author lkx Created at 2015-10-17 下午2:45:38
	 */
	private void upload() {
		if (myBitmap != null) {

			File fTemp = null;

			try {
				fTemp = File.createTempFile("letter", ".jpg");
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fTemp));

				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			ApiParam param = ApiParam.create();
			param.addParam("file", fTemp);
			Api.post("me/uploadAvatar", param, new ApiCallback(SetNameAndIconActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					if (result.getCode() == 100) {
						try {
							SharedPreferencesKit.putString(mContext, Const.SP_KEY_USER_HEADER, result.getData().getString("header"));
							AppKit.refreshRongIMUser(mContext);
						} catch (JSONException e) {
							Log.e(TAG, e.getMessage(), e);
						}
					}
				}

				@Override
				public void handleFailure(Exception e, String msg) {
				}
			}, SetNameAndIconActivity.this);
		}

	}

	// @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// super.onActivityResult(requestCode, resultCode, data);
	// Intent intent = new Intent("com.android.camera.action.CROP");
	// Uri data2 = null;
	// if (data == null) {
	// data2 = PictureUtil.getImageUri();
	// } else {
	// data2 = data.getData();
	// }
	// if (resultCode == RESULT_OK) {
	// switch (requestCode) {
	// case PictureUtil.PHOTO_PICKED_WITH_DATA:
	// intent.setDataAndType(data2, "image/*");
	// intent.putExtra("crop", true);
	// // 设置裁剪尺寸
	// intent.putExtra("aspectX", 1);
	// intent.putExtra("aspectY", 1);
	// intent.putExtra("outputX", 160);
	// intent.putExtra("outputY", 130);
	// intent.putExtra("return-data", true);
	// intent.putExtra(MediaStore.EXTRA_OUTPUT, PictureUtil.getImageCaiUri());
	// startActivityForResult(intent, PictureUtil.PHOTO_CROP);
	// break;
	// case PictureUtil.CAMERA_WITH_DATA:
	// intent.setDataAndType(data2, "image/*");
	// intent.putExtra("crop", true);
	// intent.putExtra("aspectX", 1);
	// intent.putExtra("aspectY", 1);
	// intent.putExtra("outputX", 160);
	// intent.putExtra("outputY", 130);
	// intent.putExtra("return-data", true);
	// intent.putExtra(MediaStore.EXTRA_OUTPUT, PictureUtil.getImageCaiUri());
	// startActivityForResult(intent, PictureUtil.PHOTO_CROP);
	// break;
	// case PictureUtil.PHOTO_CROP:
	// Bundle bundle = data.getExtras();
	// myBitmap = (Bitmap) bundle.get("data");
	// Bitmap bitImage = comp(myBitmap);
	//
	// String fileName = getCharacterAndNumber();
	// File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
	// saveMyBitmap(bitImage, file);
	//
	// iconImageView.setImageBitmap(bitImage);
	//
	// final Map<String, File> fileParas = new HashMap<String, File>();
	// fileParas.put("file", file);
	//
	// /**
	// * 在这里选择完毕后,直接进行了上传,在logcat中查看结果吧..
	// */
	//
	// }
	// }
	// }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径

				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {

				crop(Uri.fromFile(tempFile));
			} else {
				Toast.makeText(SetNameAndIconActivity.this, "未找到存储卡，无法存储照片！", 0).show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				myBitmap = data.getParcelableExtra("data");
				this.iconImageView.setImageBitmap(myBitmap);
				upload();
				boolean delete = tempFile.delete();

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.PNG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	// 压缩图片(第一次)
	private Bitmap comp(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 100, baos);
		if (baos.toByteArray().length / 1024 > 200) {// 判断如果图片大于200KB,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.PNG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 160f;// 这里设置高度为800f
		float ww = 130f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	public void saveMyBitmap(Bitmap mBitmap, File file) {
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			mBitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
			byte[] bitmapData = baos.toByteArray();

			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bitmapData);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 得到系统当前时间并转化为字符串
	@SuppressLint("SimpleDateFormat")
	public static String getCharacterAndNumber() {
		String rel = "";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date curDate = new Date(System.currentTimeMillis());
		rel = formatter.format(curDate);
		return rel;
	}

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 * 
	 * @author lkx Created at 2015-10-17 上午10:53:34
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 图片裁剪
	 * 
	 * @param uri
	 * 
	 * @author lkx Created at 2015-10-17 上午10:58:44
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	// /**
	// * 图片上传
	// *
	// * @param view
	// *
	// * @author lkx Created at 2015-10-17 下午12:53:52
	// */
	// public void upload() {
	// try {
	// ByteArrayOutputStream out = new ByteArrayOutputStream();
	// myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
	// out.flush();
	// out.close();
	// byte[] buffer = out.toByteArray();
	//
	// byte[] encode = Base64.encode(buffer, Base64.DEFAULT);
	// String photo = new String(encode);
	// BufferedOutputStream stream = null;
	// File file = null;
	// try {
	// file = new File(Environment.getExternalStorageDirectory(),
	// PHOTO_FILE_NAME);
	// FileOutputStream fstream = new FileOutputStream(file);
	// stream = new BufferedOutputStream(fstream);
	// stream.write(encode);
	// } catch (Exception e) {
	// e.printStackTrace();
	// } finally {
	// if (stream != null) {
	// try {
	// stream.close();
	// } catch (IOException e1) {
	// e1.printStackTrace();
	// }
	// }
	// }
	//
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
}
